package com.powernode.service.impl;

import com.powernode.constant.Constants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class LuaService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //脚本 long 值 表示lua 返回值
    private DefaultRedisScript<Long> redisScript;
    //PostConstruct 注解，在类初始化完成之后执行
    @PostConstruct
    public void init() {
        //创建lua脚本
        redisScript = new DefaultRedisScript<>();
        //设置返回值类型为Long
        redisScript.setResultType(Long.class);
        //设置lua脚本路径
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("seckill.lua")));
    }

    public Long runLua(Integer goodsId, Integer userId) {
        //限流的key  单位精确到秒
        String limitKey = System.currentTimeMillis() / 1000 + "";

        //表示用户是否秒杀过该商品
        String holdKey = Constants.REDIS_HOLD + goodsId + ":" + userId;

        //商品库存key
        String storeKey = Constants.REDIS_STORE + goodsId;

        //将key放入list中
        List<String> keyList = Arrays.asList(limitKey, holdKey, storeKey);

        //执行lua脚本并传入参数,并获取lua的返回结果
        Long executeResult = stringRedisTemplate.execute(redisScript, keyList, String.valueOf(userId), String.valueOf(Constants.MAX_LIMIT));


        return executeResult;
    }


}
